<template>
  <div class="chat-container">
    <!-- 聊天消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" 
        :key="index"
        :class="['message-item', message.isSelf ? 'message-self' : 'message-other']"
      >
        <div class="message-avatar">
          <img :src="message.avatar" :alt="message.name">
        </div>
        <div class="message-content">
          <div class="message-name">{{ message.name }}</div>
          <div class="message-bubble">
            <!-- 文本消息 -->
            <template v-if="message.type === 'text'">
              <div class="text-content">{{ message.content }}</div>
            </template>
            
            <!-- 图片消息 -->
            <template v-else-if="message.type === 'image'">
              <div class="image-content">
                <el-image 
                  :src="message.content" 
                  :preview-src-list="[message.content]"
                  fit="cover"
                  :initial-index="0"
                >
                  <template #placeholder>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </template>
            
            <!-- 文件消息 -->
            <template v-else-if="message.type === 'file'">
              <div class="file-content">
                <el-icon><Document /></el-icon>
                <div class="file-info">
                  <div class="file-name">{{ message.fileName }}</div>
                  <div class="file-size">{{ formatFileSize(message.fileSize) }}</div>
                </div>
                <el-button type="primary" link @click="downloadFile(message)">
                  下载
                </el-button>
              </div>
            </template>
          </div>
          <div class="message-time">{{ formatTime(message.time) }}</div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-upload
          class="image-upload"
          action="#"
          :show-file-list="false"
          :before-upload="handleImageUpload"
          accept="image/*"
        >
          <el-button type="primary" link>
            <el-icon><Picture /></el-icon>
          </el-button>
        </el-upload>

        <el-upload
          class="file-upload"
          action="#"
          :show-file-list="false"
          :before-upload="handleFileUpload"
        >
          <el-button type="primary" link>
            <el-icon><Folder /></el-icon>
          </el-button>
        </el-upload>
      </div>

      <!-- 文本输入框 -->
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息..."
          resize="none"
          @keydown.enter.prevent="sendMessage"
        />
        <el-button 
          type="primary" 
          :disabled="!inputMessage.trim()" 
          @click="sendMessage"
        >发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Document, Folder } from '@element-plus/icons-vue'

const props = defineProps({
  currentUser: {
    type: Object,
    required: true
  },
  otherUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['send-message'])

const messages = ref([])
const inputMessage = ref('')
const messagesContainer = ref(null)

// 滚动到底部
async function scrollToBottom() {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 发送文本消息
function sendMessage() {
  if (!inputMessage.value.trim()) return
  
  const message = {
    type: 'text',
    content: inputMessage.value,
    time: Date.now(),
    isSelf: true,
    name: props.currentUser.name,
    avatar: props.currentUser.avatar
  }
  
  messages.value.push(message)
  emit('send-message', message)
  inputMessage.value = ''
  scrollToBottom()
}

// 处理图片上传
async function handleImageUpload(file) {
  try {
    if (!file.type.includes('image/')) {
      ElMessage.error('请上传图片文件')
      return false
    }
    
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过10MB')
      return false
    }
    
    // 转换为base64预览
    const reader = new FileReader()
    reader.readAsDataURL(file)
    
    reader.onload = async (e) => {
      const message = {
        type: 'image',
        content: e.target.result,
        time: Date.now(),
        isSelf: true,
        name: props.currentUser.name,
        avatar: props.currentUser.avatar
      }
      
      messages.value.push(message)
      emit('send-message', message)
      scrollToBottom()
    }
    
    return false
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
    return false
  }
}

// 处理文件上传
async function handleFileUpload(file) {
  try {
    if (file.size > 50 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过50MB')
      return false
    }
    
    const message = {
      type: 'file',
      content: URL.createObjectURL(file),
      fileName: file.name,
      fileSize: file.size,
      time: Date.now(),
      isSelf: true,
      name: props.currentUser.name,
      avatar: props.currentUser.avatar
    }
    
    messages.value.push(message)
    emit('send-message', message)
    scrollToBottom()
    
    return false
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
    return false
  }
}

// 下载文件
function downloadFile(message) {
  const link = document.createElement('a')
  link.href = message.content
  link.download = message.fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
function formatTime(timestamp) {
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 接收消息
function receiveMessage(message) {
  messages.value.push({
    ...message,
    isSelf: false
  })
  scrollToBottom()
}

// 暴露方法给父组件
defineExpose({
  receiveMessage
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f7fa;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-self {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  margin: 0 12px;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-content {
  max-width: 60%;
}

.message-name {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-self .message-name {
  text-align: right;
}

.message-bubble {
  padding: 12px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.message-self .message-bubble {
  background: #409eff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  text-align: right;
}

.text-content {
  word-break: break-word;
  line-height: 1.5;
}

.image-content {
  max-width: 300px;
}

.image-content .el-image {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 200px;
  background: #f5f7fa;
  color: #909399;
}

.file-content {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.message-self .file-content {
  background: rgba(255,255,255,0.1);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 12px;
  color: #909399;
}

.message-self .file-size {
  color: rgba(255,255,255,0.8);
}

.chat-input {
  background: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 12px;
}

.toolbar {
  display: flex;
  gap: 12px;
  padding: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 12px 0;
}

.input-area .el-input {
  flex: 1;
}

.input-area .el-button {
  align-self: flex-end;
}
</style> 